package com.android.converter;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import android.annotation.TargetApi;
import android.os.Environment;
import android.util.Base64;



@TargetApi(8)
public class Base64Convert {

	public String plikNaBase64(String filname){
		
		try {
			
			String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + filname;
			
			File file = new File(path);
			
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			ObjectOutputStream oos;
			
			oos = new ObjectOutputStream(bos);
	
			oos.writeObject(file);
			bos.close();
			oos.close();
			
			byte[] data = bos.toByteArray();
			
			String result = Base64.encodeToString(data, Base64.DEFAULT);
			
			return result;
		
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public void base64NaPlik(String result){
		try {
			
			byte[] data = Base64.decode(result, Base64.DEFAULT);
    		
			ByteArrayInputStream bis = new ByteArrayInputStream(data);
    		
			ObjectInputStream ois = new ObjectInputStream(bis);
    		File fileFromBytes = (File) ois.readObject();
    		
    		FileOutputStream fos = new FileOutputStream(fileFromBytes);
    	    fos.write(data);
    	    fos.flush();
    	    fos.close();
  		  	
    		bis.close();
    		ois.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}		
	}
	
	
}
